package cn.pink.common.support;

import cn.pink.common.proto.MsgIds;
import cn.pink.common.support.tools.msg.MsgTool;
import cn.pink.core.support.Log;
import cn.pink.core.support.Param;
import cn.pink.core.support.SysException;
import cn.pink.core.support.Utils;
import com.google.protobuf.CodedInputStream;
import com.google.protobuf.GeneratedMessageV3;

import java.io.IOException;

/**
 * 消息发送
 * @Author: pink
 * @Date: 2022/6/30 18:51
 */
public abstract class MsgRoute {
    /**
     * 路由消息
     * @param msg msg
     * @param param param
     */
    public abstract void route(GeneratedMessageV3 msg, Param param);

    /**
     * 消息处理
     */
    public boolean handle(byte[] buffer, Object...params) {
        // 消息长度
        int len = Utils.bytesToBigEndian32(buffer, 0);
        // 消息ID
        int msgId = Utils.bytesToBigEndian32(buffer, 4);

        // 取出消息体
        CodedInputStream in = CodedInputStream.newInstance(buffer, 8, buffer.length - 8);
        try {
            GeneratedMessageV3 msg = parseFrom(msgId, in);

            if (msg == null) {
                Log.game.info("proto not exist, id={}", msgId);
                return false;
            }

            //记录日志
            MsgTool.getInstance().printMsg(msg);

            // 发送接到消息事件
            Param param = new Param(params);
            // 把msgId加入参数，不用再次获取
            param.put("msgId", msgId);

            route(msg, param);

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            throw new SysException(e);
        }
    }

    /**
     * 解析消息
     */
    public GeneratedMessageV3 parseFrom(int type, CodedInputStream s) throws IOException {
        return MsgIds.parseFrom(type, s);
    }
}
